package com.bitdf.txing.chat.utils;

import com.alibaba.fastjson.JSON;
import com.bitdf.txing.chat.constant.Constant;
import com.bitdf.txing.chat.entity.ChatMessageEntity;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lizhiwei
 * @date 2022/11/26 0:39:35
 * 注释：
 */
@Component
public class RedisUtil {
    //    @Autowired
//    private static RedisTemplate stringRedisTemplate;
    public static Boolean rightPushByList(String chatKey, List<ChatMessageEntity> list1, StringRedisTemplate stringRedisTemplate) {

        List<String> stringList = list1.stream().map((item) -> {
            return JSON.toJSONString(item);
        }).collect(Collectors.toList());
        Long aLong = stringRedisTemplate.opsForList().rightPushAll(chatKey, stringList);
        return aLong == list1.size() ? true : false;
    }

    public static List<String> objectListToStrList(List<?> list) {
        List<String> collect = list.stream().map((item) -> {
            String s = JSON.toJSONString(item);
            return s;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 把新消息存进redis中
     *
     * @param chatMessage
     * @param stringRedisTemplate
     * @return
     */
    public boolean saveChatMessage(ChatMessageEntity chatMessage, StringRedisTemplate stringRedisTemplate) {
        boolean result = false;
        String chatKey = null;
        if (chatMessage.getType() == 0) {
            long min = Math.min(chatMessage.getFromUserId(), chatMessage.getToTargetId());
            long max = Math.max(chatMessage.getFromUserId(), chatMessage.getToTargetId());
            chatKey = Constant.CHATMESSAGE_SINGLE + max + "-" + min;
        } else if (chatMessage.getType() == 1) {
            chatKey = Constant.CHATMESSAGE_GROUP + chatMessage.getToTargetId();
        }
        try {
            String s = JSON.toJSONString(chatMessage);
            stringRedisTemplate.opsForList().leftPush(chatKey, s);
//            redisTemplate.opsForList().leftPush(chatHistoryKey, chatMessage);
//            redisTemplate.expire(chatHistoryKey, 20, TimeUnit.MINUTES);
//            redisTemplate.opsForList().trim(chatHistoryKey, 0, 15);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
